package com.laicunba.ext.activity.act20170526;

import java.math.BigDecimal;
import java.util.Date;

import javax.jms.Message;
import javax.jms.TextMessage;

import org.apache.log4j.Logger;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.laicunba.ext.service.SlaveUserService;
import com.laicunba.jms.JmsQueueListener;
import com.laicunba.jms.JmsQueueListenerTemplate;
import com.laicunba.pojo.ActivityDO;
import com.laicunba.pojo.FinancingTargetBidDO;
import com.laicunba.pojo.RegistryDO;
import com.laicunba.pojo.UserDO;
import com.laicunba.service.ActivityService;
import com.laicunba.service.FinancingTargetBidService;
import com.laicunba.service.RegistryService;
import com.laicunba.service.UserService;
import com.laicunba.service.VcoinWalletService;
import com.laicunba.util.CacheUtil;
import com.laicunba.util.DateUtil;
import com.laicunba.util.StringUtil;

//@Component
public class Act20170526PaySuccessListener extends JmsQueueListenerTemplate implements JmsQueueListener {

	@Autowired
	private SlaveUserService slaveUserService;
	@Autowired
	private UserService userService;
	@Autowired
	private VcoinWalletService vcoinWalletService;
	@Autowired
	private RegistryService registryService;
	@Autowired
	private FinancingTargetBidService financingTargetBidService;
	@Autowired
	private ActivityService activityService;

	private static int HOUR24 = 3600 * 24;
	private static int MINITE10 = 600;
	private static final Logger LOG = Logger.getLogger(Act20170526PaySuccessListener.class);

	@Override
	public String queue() {
		return "lcb.core.tmp.act20170526";
	}

	@Override
	public boolean receive(Message msg) {
		TextMessage txtMsg = (TextMessage) msg;
		try {
			LOG.info(String.format("【20170526端午节活动】支付成功接收消息，txtMsg=[%s]", txtMsg.getText()));
			JSONObject msgJson = (JSONObject) new JSONParser().parse(txtMsg.getText());
			if (!msgJson.containsKey("id")) {
				return true;
			}
			
			ActivityDO activity = activityService.get(ActivityDO.class, "20170526");
			if(activity == null || activity.getBeginTime().after(new Date()) || activity.getEndTime().before(new Date())) {
				return true;
			}
			
			String bidId = msgJson.get("id").toString();
			if(StringUtil.isEmpty(bidId)) {
				return true;
			}
			
			FinancingTargetBidDO bidDO = financingTargetBidService.get(FinancingTargetBidDO.class, bidId);
			if(bidDO == null || !"CPB".equalsIgnoreCase(bidDO.getType())) {
				return true;
			}

			// 防重复
			if (CacheUtil.incr("act.20170526." + bidDO.getId(), MINITE10) > 1) {
				return true;
			}
			
			LOG.info(String.format("【20170526端午节活动】支付成功接收消息，bidUserId=[%s]", bidDO.getBidUserId()));
			if(StringUtil.isEmpty(bidDO.getBidUserId())) {
				return true;
			}

			int period = DateUtil.days(bidDO.getBeginProfit(), bidDO.getEndProfit());
			LOG.info(String.format("【20170526端午节活动】支付成功接收消息，period=[%s]", period));
			//用户投资>15天的定期加积分
			if (period > 15) {
				//清理老活动的累积积分，如果已清理则不再次进行
				RegistryDO cleanInviteVcoinRegistry = registryService.get(RegistryDO.class, "u." + bidDO.getBidUserId() + ".clean-dragon-boat-vcoin");
				if(cleanInviteVcoinRegistry == null) {
					long balance = vcoinWalletService.getBalance(bidDO.getBidUserId());
					if(balance > 0) {
						vcoinWalletService.subtract(bidDO.getBidUserId(), (int) balance, "DRAGON_BOAT_FESTIVAL_CLEAN", "端午节活动积分清零");
					}
					
					cleanInviteVcoinRegistry = new RegistryDO();
					cleanInviteVcoinRegistry.setId("u." + bidDO.getBidUserId() + ".clean-dragon-boat-vcoin");
					cleanInviteVcoinRegistry.setVal(String.valueOf(balance));
					cleanInviteVcoinRegistry.setVisible(true);
					cleanInviteVcoinRegistry.setSummary("端午节活动清除老活动的累积积分");
					registryService.create(cleanInviteVcoinRegistry);
				}
				
				LOG.info(String.format("【20170526端午节活动】支付成功接收消息，buyAmount=[%s]", bidDO.getBuyAmount()));
				if(bidDO.getBuyAmount().compareTo(BigDecimal.valueOf(1000)) < 0) {
					return true;
				}
				int vcoinAmt = bidDO.getBuyAmount().multiply(BigDecimal.valueOf(period)).divide(BigDecimal.valueOf(365), BigDecimal.ROUND_HALF_UP).intValue();
				LOG.info(String.format("【20170526端午节活动】支付成功接收消息，vcoinAmt=[%s]", vcoinAmt));
				if(vcoinAmt > 0) {
					vcoinWalletService.add(bidDO.getBidUserId(), vcoinAmt, "DRAGON_BOAT_FESTIVAL", "端午节活动期间成功投资"+bidDO.getBuyAmount()+"元/"+period+"天");
				}
			}
			
			
			//用户首投送好友里程数
			if(!financingTargetBidService.isFirstBid(bidDO.getBidUserId())){
				return true;
			}
			UserDO bidUser = userService.get(UserDO.class, bidDO.getBidUserId());
			if (bidUser == null || StringUtil.isEmpty(bidUser.getInviteFrom())) {
				return true;
			}
			//判断用户注册时间是否在活动时间内
			if(bidUser.getGmtCreate().before(activity.getBeginTime()) || bidUser.getGmtCreate().after(activity.getEndTime()) ) {
				return true;
			}
			UserDO friend = slaveUserService.findByInviteCode(bidUser.getInviteFrom());
			if(friend == null) {
				return true;
			}
			
			String key = "act.20170526chance." + friend.getId() + DateUtil.formatDate(new Date());
			String val = CacheUtil.getAttribute(key);
			LOG.info(String.format("【20170526端午节活动】支付成功接收消息，friendId=[%s],chanceKey=[%s],chance=[%s]", friend.getId(), key, val));
			if (StringUtil.isEmpty(val)) {
				CacheUtil.setAttribute(key, "1", HOUR24);
				val = "1";
			} else {
				CacheUtil.setAttribute(key, String.valueOf(Integer.parseInt(val) + 1), HOUR24);
			}
			//每人每天5次上限
			if(Integer.parseInt(val) >= 5) {
				return true;
			}
			//用户首投送好友里程数
			//清理好友老活动的累积积分，如果已清理则不再次进行
			RegistryDO cleanInviteVcoinRegistry = registryService.get(RegistryDO.class, "u." + friend.getId() + ".clean-dragon-boat-vcoin");
			if(cleanInviteVcoinRegistry == null) {
				long balance = vcoinWalletService.getBalance(friend.getId());
				if(balance > 0) {
					vcoinWalletService.subtract(friend.getId(), (int) balance, "DRAGON_BOAT_FESTIVAL_CLEAN", "端午节活动积分清零");
				}
				
				cleanInviteVcoinRegistry = new RegistryDO();
				cleanInviteVcoinRegistry.setId("u." + friend.getId() + ".clean-dragon-boat-vcoin");
				cleanInviteVcoinRegistry.setVal(String.valueOf(balance));
				cleanInviteVcoinRegistry.setVisible(true);
				cleanInviteVcoinRegistry.setSummary("端午节活动清除老活动的累积积分");
				registryService.create(cleanInviteVcoinRegistry);
			}
			vcoinWalletService.add(friend.getId(), 100, "DRAGON_BOAT_FESTIVAL", "端午节活动期间"+bidUser.getMobile()+"已注册并首投");
			LOG.info(String.format("【20170526端午节活动】支付成功接收消息处理完毕,好友积分加100 共[%s]个,好友今日通过邀请首投获取积分[%s]次", vcoinWalletService.getBalance(friend.getId()), CacheUtil.getAttribute(key)));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}
}
